package com.ruoyi.user.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.user.domain.YmCartEntity;
import com.ruoyi.user.enums.ReqHandleExceptionEnum;
import com.ruoyi.user.interceptor.LoginInterceptor;
import com.ruoyi.user.model.LoginUser;
import com.ruoyi.user.pojo.ReqHandleVo;
import com.ruoyi.user.pojo.YmCartVo;
import com.ruoyi.user.service.IYmCartService;
import com.ruoyi.user.service.IYmProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 购物车 Controller
 * 
 * @author zq
 * @date 2022-11-08
 */
@RestController
@RequestMapping("/ymapp/cart")
@Slf4j
public class YmCartController extends BaseController
{
    @Autowired
    private IYmProductService ymProductService;
    @Autowired
    private IYmCartService ymCartService;


    /**
     * 查询列表
     */
    @PreAuthorize("@ss.hasPermi('myapp:cart:list')")
    @GetMapping("/list")
    public TableDataInfo list(YmCartEntity ymCartEntity)
    {
        startPage();
        List<YmCartEntity> list = ymCartService.selectYmCartList(ymCartEntity);
        return getDataTable(list);
    }

    /**
     * 查询指定用户的商品加购列表（uid、购物车）
     * @param
     * @return
     */
    @GetMapping("/queryCartInfo")
    public ReqHandleVo<YmCartVo> queryCartInfo(){
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        Long uid = loginUser.getId();

        ReqHandleVo<YmCartVo> reqHandleVo = new ReqHandleVo<>();
        List<YmCartVo> cartInfos = ymCartService.queryCartInfoByUid(uid);
        if(CollectionUtils.isEmpty(cartInfos)){
            reqHandleVo = reqHandleVo.buildError(ReqHandleExceptionEnum.CART_IS_EMPTY.getDesc());
//            log.info("reqHandleVo = {}",reqHandleVo);
            return reqHandleVo;
        }

        reqHandleVo.setData(cartInfos);
        reqHandleVo = reqHandleVo.buildSuccess("请求成功");
//        log.info("reqHandleVo = {}",reqHandleVo);
        return reqHandleVo;

    }

    /**
     * 根据cartId和cmd操作类型修改对应商品的加购数量
     * @param
     * @return
     */
    @GetMapping("/changeNumber")
    public ReqHandleVo<YmCartVo> changeNumberByCartIdAndOpType(@RequestParam("id") Long cartId,@RequestParam("cmd") String opType){
        ReqHandleVo<YmCartVo> reqHandleVo = new ReqHandleVo<>();
        int opResult = ymCartService.changeNumberByCartIdAndOpType(cartId,opType);
        if(opResult < 1){
            reqHandleVo = reqHandleVo.buildError(ReqHandleExceptionEnum.NET_LOAD_ERROR.getDesc());
//            log.info("reqHandleVo = {}",reqHandleVo);
            return reqHandleVo;
        }

        reqHandleVo = reqHandleVo.buildSuccess("修改成功");
//        log.info("reqHandleVo = {}",reqHandleVo);
        return reqHandleVo;

    }


    /**
     * 导出列表
     */
    @PreAuthorize("@ss.hasPermi('myapp:cart:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YmCartEntity ymCartEntity)
    {
        List<YmCartEntity> list = ymCartService.selectYmCartList(ymCartEntity);
        ExcelUtil<YmCartEntity> util = new ExcelUtil<YmCartEntity>(YmCartEntity.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('myapp:cart:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(ymCartService.selectYmCartById(id));
    }

    /**
     * 新增
     */
//    @PreAuthorize("@ss.hasPermi('myapp:cart:add')")
    @PostMapping("/addCart")
    public ReqHandleVo<YmCartEntity> add(@RequestBody YmCartEntity ymCartEntity)
    {
        log.info("YmCartEntity addCart:{}",ymCartEntity);
        ReqHandleVo<YmCartEntity> reqHandleVo = new ReqHandleVo<>();
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        Long uid = loginUser.getId();
        ymCartEntity.setUid(uid);
        YmCartEntity ymCart = ymCartService.selectYmCartByCartEntityByIdAndPid(ymCartEntity);
        // 如果存在则对数量进行加一
        if (ymCart != null) {
            log.info("nums:{}",ymCart.getNumber());
            ymCart.setNumber(ymCart.getNumber()+1);
            ymCartService.updateYmCartByUidAndPid(ymCart);
            // 加购成功
            reqHandleVo = reqHandleVo.buildSuccess("添加成功！");
//        log.info("reqHanldeVo：{}",reqHandleVo);
            return reqHandleVo;
        }
        // 直接到购物车表插入1条新的加购记录
        int res = ymCartService.insertYmCart(ymCartEntity);
        // 加购失败
        if(res < 1){
            reqHandleVo = reqHandleVo.buildError(ReqHandleExceptionEnum.NET_LOAD_ERROR.getDesc());// 网络加载异常
//            log.info("reqHanldeVo：{}",reqHandleVo);
            return reqHandleVo;
        }
        // 加购成功
        reqHandleVo = reqHandleVo.buildSuccess("添加成功！");
//        log.info("reqHanldeVo：{}",reqHandleVo);
        return reqHandleVo;

    }

    /**
     * 修改
     */
    @PreAuthorize("@ss.hasPermi('myapp:product:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody YmCartEntity ymCartEntity)
    {
        return toAjax(ymCartService.updateYmCart(ymCartEntity));
    }

    /**
     * 根据cartId删除指定的商品加购记录
     */
	@DeleteMapping("/deleteCart")
    public ReqHandleVo<YmCartVo> deleteCart(@RequestBody YmCartEntity ymCartEntity)
    {
        System.out.println("ymCartEntity = " + ymCartEntity);
//        log.info("ymCartEntity:{}",id);
        ReqHandleVo<YmCartVo> reqHandleVo = new ReqHandleVo<>();

        int opResult = ymCartService.deleteYmCartById(ymCartEntity.getId());
        if(opResult < 1){
            reqHandleVo = reqHandleVo.buildError(ReqHandleExceptionEnum.NET_LOAD_ERROR.getDesc());
//            log.info("reqHandleVo = {}",reqHandleVo);
            return reqHandleVo;
        }

        reqHandleVo = reqHandleVo.buildSuccess("删除成功");
//        log.info("reqHandleVo = {}",reqHandleVo);
        return reqHandleVo;
    }
}
